import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import SearchPopup from '@/views/SearchPopup.vue'

const newRouter = VueRouter.prototype.push
VueRouter.prototype.push = function(location) {
  return newRouter.call(this, location).catch(() => {})
}

// 当做Vue插件
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      activeNum: 0,
      isShowbar: true
    },
    children: [
      {
        path: 'search',
        component: SearchPopup
      }
    ]
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: {
      activeNum: 1,
      isShowbar: true
    },
    component: () => import(/* webpackChunkName: 'Topic' */ '@/views/Topic.vue')
  },
  {
    path: '/category',
    name: 'Category',
    meta: {
      activeNum: 2,
      isShowbar: true
    },
    component: () =>
      import(/* webpackChunkName: 'Category' */ '@/views/Category.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      activeNum: 3,
      isShowbar: true
    },
    component: () => import(/* webpackChunkName: 'Cart' */ '@/views/Cart.vue')
  },
  {
    path: '/user',
    name: 'User',
    meta: {
      activeNum: 4,
      isShowbar: true
    },
    component: () => import(/* webpackChunkName: 'User' */ '@/views/User.vue')
  },
  {
    path: '/productdetail',
    name: 'ProductDetail',

    component: () =>
      import(/* webpackChunkName: 'User' */ '@/views/ProductDetail.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // localStorage.setItem('token', 'Bear xxx')
  const token = localStorage.getItem('token')
  if (to.path === '/cart') {
    if (token) {
      next()
    } else {
      next('/user')
    }
  }
  next()
})

export default router
